import { savePlayMusicHistory } from '@/utils/localStorage'

// 播放器 状态
export const state = () => ({
  currentPlayObjId: '', // 当前播放的音乐id
  currentPlayObj: {}, // 当前播放的音乐
  currentPlayList: [], // 当前播放列表 [{key,value}...]
  isPlaying: false, // 播放器是否正在播放
  isLoop: false, // 列表是否开启循环播放
  isRandom: false, // 列表是否开启随机播放模式
  miniUi: false, // 播放器全屏展示
  showPlayerUi: true, // 是否展示播放器
  historyPlayList: [] // 历史播放记录
})

export const mutations = {
  setCurrentPlayObj (state, songObj) {
    // 设置当前播放歌曲
    // 做一次本地缓存
    if (!state.currentPlayObj) {
      // 首次播放
      state.currentPlayObj = songObj
      state.currentPlayObjId = songObj.id
      savePlayMusicHistory(songObj.id, songObj.name, songObj.artists[0].name)
      return
    }
    if (songObj.id !== state.currentPlayObj.id) {
      state.currentPlayObj = songObj
      state.currentPlayObjId = songObj.id
      // 添加播放记录
      savePlayMusicHistory(songObj.id, songObj.name, songObj.artists[0].name)
    }
  },
  setCurrentPlayerList (state, vals) {
    // 设置当前播放列表
    // 比对2个对象数组id是否全部一样
    // 新数组every(久数组)
    const valsKeys = vals.map(item => item.id)
    const oldKeys = state.currentPlayList.map(item => item.id)
    const include = valsKeys.every(val => oldKeys.includes(val))
    if (!include) {
      state.currentPlayList = []
      state.currentPlayList = vals
    }
  },
  setIsPlaying (state, bool) {
    state.isPlaying = bool
  },
  setIsLoop (state, bool) {
    state.isLoop = bool
  },
  setIsRandom (state, bool) {
    state.isRandom = bool
  },
  setMiniUi (state, bool) {
    state.miniUi = bool
  },
  setShowPlayerUi (state, bool) {
    state.showPlayerUi = bool
  },
  addHistoryPlayList (state, newAdd) {
    if (!state.historyPlayList.includes(newAdd)) {
      state.historyPlayList.push(newAdd)
    } else {
      state.historyPlayList.unshift(newAdd)
      state.historyPlayList = Array.from(new Set(state.historyPlayList))
    }
    // 存入浏览器缓存中
  }
}
